// __PUBLIC__/js/page/cms/article/addpic_content
require(['../../common'], function() {
  require(['article.addpic_content'])
})

define('article.addpic_content', [
  'jquery',
  'css!ke/themes/default/default.css',
  'ke/kindeditor',
  'ke/lang/zh_CN',
  'jqp/validate',
  'css!jqp/nouislider.css',
  'jqp/nouislider',
  'css!ztree/ztree.css',
  'ztree/ztree'
], function($) {
  'use strict';

  var $form = $('#J_form'),
      picHtml = '',
      sid = $('#J_sid').val(),
      eyeHeight = (function(){
        var winHeight = $(window).height();
        if(winHeight > 620){
            return 600;
        }else{
            return winHeight - 20;
        }
      })();

  var langType = document.documentElement.lang || 'zh-CN'
    var langMap = {
      'zh-CN': 'zh_CN',
      'zh-TW': 'zh_TW',
      'en-US': 'en'
    }
  var editor = KindEditor.editor({
    allowFileManager: true,
    langType: langMap[langType],
    uploadJson: APP + "?app=cms&m=Article&a=uploadFile&sid=" + sid
  })
  KindEditor.loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(KindEditor.VERSION))

  KindEditor('#select_related_articles').click(function() {
    var url = $(this).data('url')
    var dialog = KindEditor.dialog({
      width: 800,
      height: eyeHeight,
      title: '选择相关文章',
      body: '<iframe id="content-frame" name="contentFrame" frameborder="0" src="' + url + '"></iframe>',
      closeBtn: {
        name: '关闭',
        click: function(e) {
          dialog.remove();
        }
      },
      yesBtn: {
        name: '确定',
        click: function(e) {
          var arr = []
          var oldval = []
          var i = 0
          var html = ""
          $('#content-frame').contents().find('tbody').find(':checked').each(function() {
            arr.push($(this).closest('tr').data('value'))
          })

          $("input[name^='related_articles']").each(
            function() {
              oldval[i] = $(this).val();
              i++;
            }
          )

          for (var i = 0; i < arr.length; i++) {
            var val = arr[i].split("_");
            var url = APP + "?app=cms&m=Article&a=preview&id=" + val[0];
            if ($.inArray(arr[i], oldval) > -1) {
              continue;
            }
            html += '<p id="related_articles_' + val[0] + '">';
            html += '<input type="hidden" name="related_articles[]" value="' + arr[i] + '"/>';
            html += '<a href="' + url + '"  target="_blank" class="ico_top">' + val[1] + '</a>&nbsp;&nbsp; ';
            html += '<a href="javascript:;" id="J_relatedRemove" data-aid="' + val[0] + '" class="ico_top" >取消</a><br/></p>';
          }
          $("#related_articles_div").append(html);
          dialog.remove();
        }
      },
      noBtn: {
        name: '取消',
        click: function(e) {
          dialog.remove();
        }
      }
    });
  })

  KindEditor('#select_block_articles').click(function() {
    selBlock()
  })

  KindEditor('#J_selectPic').click(function() {
    editor.loadPlugin('multiimage', function() {
      editor.plugin.multiImageDialog({
        clickFn: function(urlList) {
          KindEditor.each(urlList, function(i, data) {
            var html = ''
            html += '<input type="text" name="imageurl[]" value="' + data.url + '" class="input-text">&nbsp;&nbsp;图片描述: '
            html += '<input type="text" name="imagedes[]" class="input-text" value=""><br/>'
            $('#J_imageUpload').append(html)
          });
          editor.hideDialog();
        }
      });
    });
  });

  function countNumber(el, b) {
    var length = $(el).val().length
    $(b).html(length)
  }

  function selBlock() {
    var dialog = KindEditor.dialog({
      width: 400,
      height: eyeHeight,
      title: '选择区块',
      body: '<div id="dialoghtml" style="margin:10px;overflow:auto;">' + '<div class="zTreeDemoBackground left"  style="height:100%;width:181px;overflow:auto;">' + '<ul id="dialog_treeDemo" class="ztree" style="margin-top:10px;"></ul>' + '</div></div>',
      closeBtn: {
        name: '关闭',
        click: function(e) {
          e.preventDefault()
          dialog.remove();
        }
      },
      yesBtn: {
        name: '确定',
        click: function(e) {
          e.preventDefault()
          var treeObj = $.fn.zTree.getZTreeObj("dialog_treeDemo"),
            nodes = treeObj.getCheckedNodes(),
            html = ''

          for (var i = 0; i < nodes.length; i++) {
            if (nodes[i]['isParent'] === false) {
              html += '<p id="block_articles_' + nodes[i]['id'] + '">';
              html += '<input type="hidden" name="block_articles[]" value="' + nodes[i]['id'] + '"/>';
              html += '<label>' + nodes[i]['name'] + ' </label>';
              html += '<a href="javascript:;" id="J_blockRemove" data-aid="' + nodes[i]['id'] + '" class="ico_top" >取消</a><br/></p>';
            }
          }
          $('#block_articles_div').html(html)
          dialog.remove();
        }
      },
      noBtn: {
        name: '取消',
        click: function(e) {
          e.preventDefault()
          dialog.remove();
        }
      }
    });
    var setting = {
      check: {
        enable: true
      },
      data: {
        simpleData: {
          enable: true
        }
      },
    };
    $.ajax({
      async: false,
      cache: false,
      type: 'POST',
      dataType: "json",
      url: APP + '?app=cms&m=Block&a=getBlockInfo', //请求的action路径
      data: {
        id: 1
      },
      success: function(data) { //请求成功后处理函数。
        $.fn.zTree.init($("#dialog_treeDemo"), setting, data['children']);
      }
    });
  }

  $(document)
    .on('click', '#J_stitle', function(e) {
      var isCheck = $(this).prop('checked');
      if (isCheck) {
        $('.J_stitle').show()
      } else {
        $('.J_stitle').hide()
      }
    })
    .on('click', '#J_smore', function(e) {
      var isCheck = $(this).prop('checked');
      if (isCheck) {
        $('.J_smore').show()
      } else {
        $('.J_smore').hide()
      }
    })
    .on('click', '#J_relatedRemove', function(e) {
      e.preventDefault()
      $('#related_articles_' + $(this).data('aid')).remove()
    })
    .keydown(function(e) {
      if (e.keyCode === 83 && e.ctrlKey) {
        e.preventDefault()
        $form.submit()
      }
    })
    .on('click', '#J_blockRemove', function(e) {
      e.preventDefault()
      var aid = $(this).data('aid'),
        id = $('#J_id').val()

        // 取消的同时删除对应区块

        $.post(APP + '?app=cms&m=Article&a=delBlockByContentID', {
          id: aid,
          contentID: id
        }).done(function(res) {
          if (res === '1') {
            $('#block_articles_' + aid).remove()
          }
        })
    })
    .on('submit', $form, function(e) {
      var newPicHtml = ''
      $('input[name="imageurl[]"]').each(function() {
        newPicHtml += $(this).val()
      })
      $('input[name="imagedes[]"]').each(function() {
        newPicHtml += $(this).val()
      })

      if (newPicHtml !== picHtml) {
        $('#pic_ischange').val('Y')
      }

      $(this).submit()
      e.preventDefault()
    })
    .ready(function() {
      $('.staff').bind('focus keyup input paste', function() {
        countNumber(this, '.word_count')
      })
      $('.J_subtitle').bind('focus keyup input paste', function() {
        countNumber(this, '.J_sword')
      })

      $('input[name="imageurl[]"]').each(function() {
        picHtml += $(this).val()
      })
      $('input[name="imagedes[]"]').each(function() {
        picHtml += $(this).val()
      })

      countNumber('.staff', '.word_count')
      countNumber('.J_subtitle', '.J_sword')
    })

  var Link = $.noUiSlider.Link
  var $weight = $('#J_weight')
  var weight = parseInt($weight.val(), 10) || 60
  $("#range-slider").noUiSlider({
    start: weight,
    step: 1,
    range: {
      'min': 0,
      'max': 100
    },
    serialization: {
      lower: [
        new Link({
          target: $weight
        })
      ],
      format: {
        decimals: 0
      }
    }
  })


  $form.validate({
    classPlace: '.kv',
    errorPlace: '.kv-error',
    errors: {
      'title': {
        required: '文章标题不能为空'
      }
    }
  })
})